const express = require('express');
const router = express.Router();
const https = require("https");
const url = require("url");
const Zlib = require("zlib");
const sitemap = require("sitemap");
const replacestream = require("replacestream");
const randomstring = require("randomstring");
let sukebeiviews = require("./sukebeiviews");
let funviews = require("./funviews");
let good_clients = require("../../good-clients");


router.all("/*", function ban_robots(req, res, next) {
  let user_agent = req.headers['user-agent'];
  if (user_agent.includes("MJ12bot")) return;

  next();
});

router.all("/*", function auth(req, res, next) {
  let ip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  if (good_clients.isGoodIp(ip)) {
    return next();
  }
  if (good_clients.isGoodCookie(req.cookies['_nyaa'])) {
    return next();
  }
  /**@description WebTorrent 下载种子 可以不需要认证 */
  if(req.headers['user-agent']){
    let ua = req.headers['user-agent'];
    if(String(ua).toUpperCase().includes("TORRENT")){
      return next();
    }
  }
  if (req.headers['authorization']) {
    // debugger
    //username=nyaa
    //password=anime65
    if (req.headers['authorization'] == "Basic bnlhYTphbmltZTY1") {
      good_clients.addGoodIp(ip);
      let c = ""+randomstring.generate(5);
      good_clients.addGoodCookie(c);
      res.cookie("_nyaa", c, {
        httpOnly: true,
        domain: "nyaa.liblu.me"
      })
      res.redirect("/?nyaa-love");
    } else {
      res.send(403, "403 Forbidden")
    }
  } else {
    res.status(401);
    res.setHeader("WWW-Authenticate", "Basic realm=nyaa");
    res.send();
  }
})


router.get("/robots.txt", function robots(req, res) {
  res.contentType("text");
  let sitemap = req.protocol + "://" + req.hostname + "/sitemap.xml";
  let host = req.hostname;
  res.send(`
  UserAgent:*
  Sitemap:${sitemap}
  Sitemap:http://sukebei.nyaa.liblu.me/sitemap.xml
  Sitemap:http://nyaa.liblu.me/sitemap.xml
  Sitemap:http://nyaa.cloudno.de/sitemap.xml
  Host:${host}
  `);
});
router.get("/sitemap.xml", function sitemapOfSukebei(req, res, next) {
  if (req.headers['x-sukebei'] || req.host == "s.nyaa.liblu.me" || req.host == "sukebei.nyaa.liblu.me") {
    let sm = sitemap.createSitemap({
      hostname: req.protocol + "://" + req.hostname,
      cacheTime: 60000,
      urls: sukebeiviews.map(viewid => `${req.protocol + "://" + req.hostname}/view/${viewid}`)
    });
    sm.toXML(function (err, xml) {
      if (err) {
        res.status(500);
        res.setHeader("X-DEBUG-HOST", req.hostname);
        res.setHeader("X-DEBUG-PROTOCAL", req.protocol);
        res.send(err);
      } else {
        res.header('Content-Type', 'application/xml');
        res.send(xml);
      }
    });
  } else {
    next();
  }
});

router.get("/sitemap.xml", function sitemapOfFun(req, res) {
  let sm = sitemap.createSitemap({
    hostname: req.protocol + "://" + req.hostname,
    cacheTime: 60000,
    urls: funviews.map(viewid => `${req.protocol + "://" + req.hostname}/view/${viewid}`)
  });
  sm.toXML(function (err, xml) {
    if (err) {
      res.status(500);
      res.setHeader("X-DEBUG-HOST", req.hostname);
      res.setHeader("X-DEBUG-PROTOCAL", req.protocol);
      res.send(err);
    } else {
      res.header('Content-Type', 'application/xml');
      res.send(xml);
    }
  });
});

router.get("/yandex_0628bd6cbb5901ec.html", function (req, res) {
  res.send(
    `
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>Verification: 0628bd6cbb5901ec</body>
</html>
    `
  )
})

let nyaaRoutePaths = ["/", "/view", "/login", "/register", "/help", "/rules", "/user", "/upload"];
router.use(nyaaRoutePaths, function intoSukebei(req, res, next) {
  if (req.headers['x-sukebei'] || req.host == "s.nyaa.liblu.me" || req.host == "sukebei.nyaa.liblu.me") {
    // res.send("wait for sukebei...");
    let nyaa = `https://sukebei.nyaa.si${req.originalUrl}`;
    // console.log("remote url is ..", nyaa);
    let parsedNyaa = url.parse(nyaa);
    let headers = req.headers;
    let myhost = headers['host'];
    headers['host'] && (headers['host'] = parsedNyaa.host);
    headers['referer'] && (headers['referer'] = nyaa);
    headers['referrer'] && (headers['referrer'] = nyaa);
    headers['origin'] && (headers['origin'] = `${parsedNyaa.protocol}//${parsedNyaa.host}${parsedNyaa.port ? (':' + parsedNyaa.port) : ''}`);
    // console.log("headers are ", headers);
    let request = https.request({
      hostname: parsedNyaa.hostname,
      method: req.method,
      headers: req.headers,
      path: parsedNyaa.path,
      search: parsedNyaa.search
    }, (httpRes) => {
      for (let h in httpRes.headers) {
        if (h == "set-cookie") {
          let cookietext = httpRes.headers[h];
          if (cookietext.includes("nyaa.si")) {
            cookietext = cookietext.replace("nyaa.si", req.hostname);
            res.setHeader(h, cookietext);
          }
        } else {
          res.setHeader(h, httpRes.headers[h]);
        }
      }
      if (httpRes.headers['content-type'].includes("text/html")) {
        let gunzip = Zlib.createGunzip();
        let gzip = Zlib.createGzip();
        httpRes
          .pipe(gunzip)
          .pipe(replacestream(/<link.*(sukebei\.nyaa\.si).*>/i, (raw, nyaasi) => {
            return raw.replace(nyaasi, myhost)
          }))
          .pipe(replacestream(/<a.*(nyaa\.si).*/i, function (raw, nyaa) {
            return raw.replace(nyaa, "nyaa.liblu.me")
          }))
          .pipe(gzip)
          .pipe(res);
      } else {
        httpRes.pipe(res);
      }

    });
    request.on("error", (err) => {
      res.send(500, err);
    })
    req.pipe(request);
  } else {
    next();
  }
});

router.use(nyaaRoutePaths, function fun(req, res) {
  let nyaa = `https://nyaa.si${req.originalUrl}`;
  // console.log("remote url is ..", nyaa);
  let parsedNyaa = url.parse(nyaa);
  let headers = req.headers;
  let myhost = headers['host'];
  headers['host'] && (headers['host'] = parsedNyaa.host);
  headers['referer'] && (headers['referer'] = nyaa);
  headers['referrer'] && (headers['referrer'] = nyaa);
  headers['origin'] && (headers['origin'] = `${parsedNyaa.protocol}//${parsedNyaa.host}${parsedNyaa.port ? (':' + parsedNyaa.port) : ''}`);
  // console.log("headers are ", headers);
  let request = https.request({
    hostname: parsedNyaa.hostname,
    method: req.method,
    headers: req.headers,
    path: parsedNyaa.path,
    search: parsedNyaa.search
  }, (httpRes) => {
    for (let h in httpRes.headers) {
      if (h == "set-cookie") {
        let cookietext = httpRes.headers[h];
        if (cookietext && cookietext.includes("nyaa.si")) {
          cookietext = cookietext.replace("nyaa.si", req.hostname);
          res.setHeader(h, cookietext);
        }
      } else {
        res.setHeader(h, httpRes.headers[h]);
      }
    }
    if (httpRes.headers['content-type'] && httpRes.headers['content-type'].includes("text/html")) {
      let gunzip = Zlib.createGunzip();
      let gzip = Zlib.createGzip();
      httpRes
        .pipe(gunzip)
        .pipe(replacestream(/<link.*(nyaa\.si).*>/i, (raw, nyaasi) => {
          return raw.replace(/nyaa\.si/i, myhost)
        }))
        .pipe(replacestream(/<a.*(sukebei\.nyaa\.si).*/i, function (raw, nyaa) {
          return raw.replace(nyaa, "s.nyaa.liblu.me")
        }))
        .pipe(gzip)
        .pipe(res);
    } else {
      httpRes.pipe(res);
    }

  });
  request.on("error", (err) => {
    res.send(500, err);
  })
  req.pipe(request);
})


module.exports = router;
